/* Copyright 2010 Hugh Greenberg */   

package com.hugegreenbug.msoss;

import java.util.ArrayList;
import java.util.Iterator;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Paint;

import com.android.graphics.spritetext.LabelMaker;

public class Text {
	private LabelMaker mLabelMaker;
	private Paint mLabelPaint;
	private int mCanvasWidth, mCanvasHeight;
	private int mTexWidth, mTexHeight;
	private int startY, startX;
	private int mMarginX, mMarginY;
	private float mTextSize;
	private int mColor;
	private ArrayList<Integer> mLabels;
	private String[] mLines;
	private boolean mColorChanged;
	private boolean mTextSizeChanged;
	
	public Text(int canvasWidth, int canvasHeight, int texWidth, int texHeight, 
				float size, int color) {
		mLabelMaker = null;
		mTextSize = size;
		mLabelPaint = new Paint();
		mColor = color;
		mLabelPaint.setColor(mColor);
		mLabelPaint.setTextSize(size);
		mLabelPaint.setAntiAlias(true);
		mCanvasWidth = canvasWidth;
		mCanvasHeight = canvasHeight;
		mTexWidth = texWidth;
		mTexHeight = texHeight;
		mMarginX = (int) ((float) canvasWidth * .03);
		mMarginY = (int) ((float) canvasHeight * .06);
		if (mMarginY < 45)
			mMarginY = 45;
		
		startY = mCanvasHeight - mMarginY;
		startX = mMarginX; 
		mLabels = new ArrayList<Integer>();
		mColorChanged = false;
		mTextSizeChanged = false;
		mLines = null;
	}
	
	public void initialize(GL10 gl) {
		if (mLabelMaker == null ) {
			mLabelMaker = new LabelMaker(true, mTexWidth, mTexHeight);
	    }
		
 		mLabelMaker.initialize(gl);
	}
	
	public void addText(GL10 gl, String[] lines) {
		if (lines == mLines && !mColorChanged && !mTextSizeChanged)
			return;
		
		mLines = lines;
		mLabels.clear();
		mLabelMaker.beginAdding(gl);
		for (int i = 0; i < lines.length; i++) {
			int label = mLabelMaker.add(gl, lines[i], mLabelPaint);	
			mLabels.add(new Integer(label));
		}
		
		mLabelMaker.endAdding(gl);
	}
	
	public void draw(GL10 gl) {
		int y = startY;
		int x = startX;
		
		Iterator<Integer> it = mLabels.iterator();
		while (it.hasNext()) {
			Integer label = it.next();
			float base = mLabelMaker.getBaseline(label.intValue());
			if (x != mMarginX && (mLabelMaker.getWidth(label.intValue()) + x >= mCanvasWidth - mMarginX * 2)) {
				y -= base;
				x = startX;
			} if (y == startY) {
				while (y > mCanvasHeight - base - mMarginY) {
					y -= 5;
				}
			}
			
			mLabelMaker.beginDrawing(gl, mCanvasWidth, mCanvasHeight);
			mLabelMaker.draw(gl, x, y, label.intValue());
			x += mLabelMaker.getWidth(label.intValue()) + mMarginX;
			mLabelMaker.endDrawing(gl);
		}
	}
	
	public void shutdown(GL10 gl) {
		mLabelMaker.shutdown(gl);
		mLabelMaker = null;
		mLines = null;
	}
       
	public void setColor(int color) {
		mColor = color;
		mLabelPaint.setColor(mColor);
		mColorChanged = true;
	}
	
	public void setTextSize(float size) {
		mTextSize = size;
		mLabelPaint.setTextSize(mTextSize);
		mTextSizeChanged = true;
	}
}
